import 'package:flutter/material.dart';
import '../models/order.dart';
import '../widgets/grab_order_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../pages/chat_page.dart';
import '../models/conversation.dart';  // 添加导入

class OrderDetailPage extends StatefulWidget {
  final Order order;

  const OrderDetailPage({
    super.key,
    required this.order,
  });

  @override
  State<OrderDetailPage> createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  final ImagePicker _picker = ImagePicker();

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 72,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 14,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 拨打电话
  void _makePhoneCall(BuildContext context, String phoneNumber) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认拨打'),
        content: Text('是否拨打 $phoneNumber？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 使用系统自带的方式打开拨号盘
              final Uri telUri = Uri(
                scheme: 'tel',
                path: phoneNumber,
              );
              try {
                // 这里不直接拨打，而是打开拨号盘让用户确认
                Navigator.pushNamed(context, telUri.toString());
              } catch (e) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('无法拨打电话'),
                    behavior: SnackBarBehavior.floating,
                  ),
                );
              }
            },
            child: const Text(
              '拨打',
              style: TextStyle(
                color: Color(0xFFFF5722),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 打开导航
  void _openNavigation(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择导航方式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Image.network(
                'https://api.iconify.design/simple-icons/autonavi.svg?color=blue',
                width: 24,
                height: 24,
                errorBuilder: (context, error, stackTrace) => const Icon(
                  Icons.map_outlined,
                  color: Colors.blue,
                ),
              ),
              title: const Text('高德地图'),
              onTap: () {
                Navigator.pop(context);
                final Uri mapUri = Uri.parse(
                  'amapuri://route/plan/?dlat=39.98848&dlon=116.47747&dname=${widget.order.address}&dev=0&t=0',
                );
                try {
                  Navigator.pushNamed(context, mapUri.toString());
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('未安装高德地图'),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                }
              },
            ),
            ListTile(
              leading: Image.network(
                'https://api.iconify.design/simple-icons/baidumap.svg?color=green',
                width: 24,
                height: 24,
                errorBuilder: (context, error, stackTrace) => const Icon(
                  Icons.map_outlined,
                  color: Colors.green,
                ),
              ),
              title: const Text('百度地图'),
              onTap: () {
                Navigator.pop(context);
                final Uri mapUri = Uri.parse(
                  'baidumap://map/direction?destination=${widget.order.address}&coord_type=bd09ll&mode=driving',
                );
                try {
                  Navigator.pushNamed(context, mapUri.toString());
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('未安装百度地图'),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                }
              },
            ),
            ListTile(
              leading: Image.network(
                'https://api.iconify.design/simple-icons/tencentqq.svg?color=orange',
                width: 24,
                height: 24,
                errorBuilder: (context, error, stackTrace) => const Icon(
                  Icons.map_outlined,
                  color: Colors.orange,
                ),
              ),
              title: const Text('腾讯地图'),
              onTap: () {
                Navigator.pop(context);
                final Uri mapUri = Uri.parse(
                  'qqmap://map/routeplan?type=drive&to=${widget.order.address}',
                );
                try {
                  Navigator.pushNamed(context, mapUri.toString());
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('未安装腾讯地图'),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  // 拍照记录
  Future<void> _takePhoto() async {
    try {
      final XFile? photo = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
      );
      
      if (photo != null && mounted) {
        // TODO: 上传图片到服务器
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.file(
                    File(photo.path),
                    fit: BoxFit.cover,
                  ),
                ),
                const SizedBox(height: 16),
                TextField(
                  maxLines: 3,
                  decoration: const InputDecoration(
                    hintText: '添加图片说明（选填）',
                    border: OutlineInputBorder(),
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  // TODO: 保存图片和说明
                  Navigator.pop(context);
                },
                style: TextButton.styleFrom(
                  foregroundColor: const Color(0xFFFF5722),
                ),
                child: const Text('保存'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('拍照失败，请重试'),
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
  }

  // 添加备注
  void _addNote() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加备注'),
        content: TextField(
          maxLines: 5,
          maxLength: 200,
          decoration: const InputDecoration(
            hintText: '请输入备注内容',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              // TODO: 保存备注
              Navigator.pop(context);
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFFF5722),
            ),
            child: const Text('保存'),
          ),
        ],
      ),
    );
  }

  // 联系客服
  void _contactCustomerService() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(
          conversation: Conversation(
            id: 'cs_${widget.order.id}',
            name: '客服中心',
            avatar: 'assets/images/customer_service.png',
            customerAvatar: 'assets/images/avatar.png',
            customerName: widget.order.customerName,
            orderType: widget.order.serviceType ?? '未知类型',  // 提供默认值
            unread: 0,
            orderId: widget.order.id,
          ),
        ),
      ),
    );
  }

  // 修改订单
  void _editOrder() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: const BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: Color(0xFFEEEEEE)),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '修改订单',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.close),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  // TODO: 添加修改表单
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () {
                        // TODO: 保存修改
                        Navigator.pop(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFFF5722),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                      ),
                      child: const Text('保存修改'),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        title: const Text(
          '订单详情',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w500,
          ),
        ),
        centerTitle: true,
        actions: [
          // 添加分享按钮
          IconButton(
            onPressed: () {
              // TODO: 实现分享功能
            },
            icon: const Icon(Icons.share_outlined),
            color: Colors.grey[700],
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 订单状态卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFFFF3E0),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          widget.order.status,
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0xFFFF5722),
                          ),
                        ),
                      ),
                      const Spacer(),
                      Text(
                        widget.order.time,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Row(
                    children: [
                      Text(
                        '订单金额',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                      const Spacer(),
                      Text(
                        '¥${widget.order.price.toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 24,  // 调大字号
                          color: Color(0xFFFF5722),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // 地址信息卡片
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题和距离信息
                  Row(
                    children: [
                      const Text(
                        '地址信息',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.blue[50],
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.directions_car,
                              size: 14,
                              color: Colors.blue[700],
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '${widget.order.distance.toStringAsFixed(1)}km',
                              style: TextStyle(
                                fontSize: 13,
                                color: Colors.blue[700],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  // 地址信息容器
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: const Color(0xFFFAFAFA),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: const Color(0xFFEEEEEE),
                      ),
                    ),
                    child: Column(
                      children: [
                        // 搬出地址
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: BoxDecoration(
                                color: Colors.green[50],
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Icon(
                                Icons.trip_origin,
                                size: 14,
                                color: Colors.green[600],
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                widget.order.fromAddress,
                                style: const TextStyle(
                                  fontSize: 15,
                                  height: 1.4,
                                ),
                              ),
                            ),
                            IconButton(
                              onPressed: () {
                                // TODO: 复制地址
                              },
                              icon: const Icon(Icons.copy_outlined),
                              iconSize: 18,
                              color: Colors.grey[400],
                              padding: EdgeInsets.zero,
                              constraints: const BoxConstraints(),
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),
                        // 搬入地址
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 20,
                              height: 20,
                              decoration: BoxDecoration(
                                color: Colors.red[50],
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Icon(
                                Icons.location_on,
                                size: 14,
                                color: Colors.red[600],
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                widget.order.address,
                                style: const TextStyle(
                                  fontSize: 15,
                                  height: 1.4,
                                ),
                              ),
                            ),
                            IconButton(
                              onPressed: () {
                                // TODO: 复制地址
                              },
                              icon: const Icon(Icons.copy_outlined),
                              iconSize: 18,
                              color: Colors.grey[400],
                              padding: EdgeInsets.zero,
                              constraints: const BoxConstraints(),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 物品清单卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Text(
                        '物品清单',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      TextButton(
                        onPressed: () {
                          // TODO: 添加物品
                        },
                        style: TextButton.styleFrom(
                          padding: EdgeInsets.zero,
                          minimumSize: const Size(0, 0),
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.add,
                              size: 16,
                              color: Colors.blue[700],
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '添加物品',
                              style: TextStyle(
                                fontSize: 13,
                                color: Colors.blue[700],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  // 物品列表
                  ListView.separated(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: 3,
                    separatorBuilder: (context, index) => const Divider(height: 16),
                    itemBuilder: (context, index) => Row(
                      children: [
                        Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Icon(
                            Icons.chair_outlined,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '沙发',
                                style: const TextStyle(
                                  fontSize: 15,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '三人座，需要拆装',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Text(
                          '×1',
                          style: TextStyle(
                            fontSize: 15,
                            color: Colors.grey[700],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 搬运工具卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '搬运工具',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 12),  // 减小间距
                  Container(
                    padding: const EdgeInsets.all(12),  // 添加内边距
                    decoration: BoxDecoration(
                      color: const Color(0xFFFAFAFA),  // 添加背景色
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: const Color(0xFFEEEEEE),
                      ),
                    ),
                    child: Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        '手推车',
                        '工具箱',
                        '打包带',
                        '纸箱',
                        '气泡膜',
                      ].map((tool) => Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,  // 改为白色背景
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(  // 添加边框
                            color: const Color(0xFFEEEEEE),
                          ),
                        ),
                        child: Text(
                          tool,
                          style: TextStyle(
                            fontSize: 13,
                            color: Colors.grey[700],
                          ),
                        ),
                      )).toList(),
                    ),
                  ),
                ],
              ),
            ),
            // 搬运人员卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '搬运人员',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 16),
                  ListView.separated(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: 2,
                    separatorBuilder: (context, index) => const SizedBox(height: 12),
                    itemBuilder: (context, index) => Row(
                      children: [
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.person_outline,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '张师傅${index + 1}',
                                style: const TextStyle(
                                  fontSize: 15,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '工号: SF88888${index + 1}',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ],
                          ),
                        ),
                        IconButton(
                          onPressed: () => _makePhoneCall(context, widget.order.customerPhone),
                          icon: const Icon(Icons.phone_outlined),
                          color: const Color(0xFFFF5722),
                          padding: EdgeInsets.zero,
                          constraints: const BoxConstraints(),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // 订单信息卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '订单信息',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 16),
                  _buildInfoRow('订单编号', widget.order.id),
                  _buildInfoRow('服务类型', widget.order.serviceType),
                  _buildInfoRow('联系人', widget.order.customerName),
                  _buildInfoRow('联系电话', widget.order.customerPhone),
                  _buildInfoRow('预约时间', widget.order.time),
                  if (widget.order.requirements.isNotEmpty)
                    _buildInfoRow('服务要求', widget.order.requirements.join('、')),
                ],
              ),
            ),
            // 订单轨迹卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '订单轨迹',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 轨迹时间线
                  _buildTimelineItem(
                    time: '2024-03-21 14:30',
                    title: '订单完成',
                    content: '已确认完成搬家服务',
                    isLast: false,
                  ),
                  _buildTimelineItem(
                    time: '2024-03-21 13:45',
                    title: '添加照片',
                    content: '上传了3张照片',
                    hasImage: true,
                    images: [
                      'https://picsum.photos/200/200?random=1',
                      'https://picsum.photos/200/200?random=2',
                      'https://picsum.photos/200/200?random=3',
                    ],
                    isLast: false,
                  ),
                  _buildTimelineItem(
                    time: '2024-03-21 12:30',
                    title: '添加备注',
                    content: '已到达目的地，正在搬运物品',
                    isLast: false,
                  ),
                  _buildTimelineItem(
                    time: '2024-03-21 10:15',
                    title: '开始服务',
                    content: '已到达上门地址，开始装车',
                    isLast: false,
                  ),
                  _buildTimelineItem(
                    time: '2024-03-21 10:00',
                    title: '接单',
                    content: '师傅已接单',
                    isLast: true,
                  ),
                ],
              ),
            ),
            // 订单操作卡片
            Container(
              margin: const EdgeInsets.all(12),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '订单操作',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 操作按钮组 - 第一行
                  Row(
                    children: [
                      _buildOperationButton(
                        icon: Icons.camera_alt_outlined,
                        label: '拍照记录',
                        onTap: _takePhoto,
                      ),
                      const SizedBox(width: 12),
                      _buildOperationButton(
                        icon: Icons.note_alt_outlined,
                        label: '添加备注',
                        onTap: _addNote,
                      ),
                      const SizedBox(width: 12),
                      _buildOperationButton(
                        icon: Icons.chat_outlined,
                        label: '联系客服',
                        onTap: _contactCustomerService,
                      ),
                    ],
                  ),
                  // 根据状态显示第二行按钮
                  if (widget.order.status == '服务中' || widget.order.status == '待服务') ...[
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        _buildOperationButton(
                          icon: Icons.edit_outlined,
                          label: '修改订单',
                          onTap: _editOrder,
                        ),
                        const SizedBox(width: 12),
                        _buildOperationButton(
                          icon: Icons.cancel_outlined,
                          label: '取消订单',
                          onTap: () {
                            _showCancelOrderDialog();
                          },
                        ),
                        const SizedBox(width: 12),
                        _buildOperationButton(
                          icon: Icons.phone_outlined,
                          label: '联系客户',
                          onTap: () {
                            _makePhoneCall(context, widget.order.customerPhone);
                          },
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
            // 底部边距
            const SizedBox(height: 24),
          ],
        ),
      ),
      bottomNavigationBar: _buildBottomBar(),  // 使用单独的方法构建底部栏
    );
  }

  /// 构建底部操作栏
  Widget? _buildBottomBar() {
    // 根据订单状态返回不同的底部操作栏
    switch (widget.order.status) {
      case '待抢单':
        return _buildGrabOrderBar();
      case '待服务':
        return _buildWaitingServiceBar();
      case '服务中':
        return _buildInServiceBar();
      case '已完成':
      case '已取消':
        return null;  // 已完成和已取消状态不显示底部栏
      default:
        return null;
    }
  }

  /// 构建抢单状态的底部栏
  Widget _buildGrabOrderBar() {
    return Container(
      padding: EdgeInsets.only(
        left: 16,
        right: 16,
        top: 12,
        bottom: MediaQuery.of(context).padding.bottom + 12,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(
            color: Color(0xFFEEEEEE),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 价格显示
          Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '订单金额',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 2),
              Text(
                '¥${widget.order.price.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFFFF5722),
                ),
              ),
            ],
          ),
          const SizedBox(width: 24),
          // 抢单按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () async {
                // 显示抢单确认对话框
                final bool? confirm = await showDialog<bool>(
                  context: context,
                  builder: (context) => GrabOrderDialog(
                    price: widget.order.price,
                    address: widget.order.address,
                    distance: widget.order.distance,
                    onConfirm: () => Navigator.pop(context, true),
                    onCancel: () => Navigator.pop(context, false),
                  ),
                );

                if (confirm == true && mounted) {
                  // TODO: 处理抢单成功
                  Navigator.pop(context, true);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF5722),
                foregroundColor: Colors.white,
                elevation: 0,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('立即抢单'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建待服务状态的底部栏
  Widget _buildWaitingServiceBar() {
    return Container(
      padding: EdgeInsets.only(
        left: 16,
        right: 16,
        top: 12,
        bottom: MediaQuery.of(context).padding.bottom + 12,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(
            color: Color(0xFFEEEEEE),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 联系客户按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () => _makePhoneCall(context, widget.order.customerPhone),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFF5F5F5),
                foregroundColor: Colors.black87,
                elevation: 0,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('联系客户'),
            ),
          ),
          const SizedBox(width: 12),
          // 开始服务按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () {
                // TODO: 处理开始服务
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF5722),
                foregroundColor: Colors.white,
                elevation: 0,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('开始服务'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建服务中状态的底部栏
  Widget _buildInServiceBar() {
    return Container(
      padding: EdgeInsets.only(
        left: 16,
        right: 16,
        top: 12,
        bottom: MediaQuery.of(context).padding.bottom + 12,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(
            color: Color(0xFFEEEEEE),
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          // 联系客户按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () => _makePhoneCall(context, widget.order.customerPhone),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFF5F5F5),
                foregroundColor: Colors.black87,
                elevation: 0,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('联系客户'),
            ),
          ),
          const SizedBox(width: 12),
          // 完成订单按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () {
                // TODO: 处理完成订单
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF5722),
                foregroundColor: Colors.white,
                elevation: 0,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('完成订单'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildOperationButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return Expanded(
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            color: const Color(0xFFF5F5F5),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Icon(
                icon,
                size: 24,
                color: Colors.grey[700],
              ),
              const SizedBox(height: 4),
              Text(
                label,
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建时间线项目
  Widget _buildTimelineItem({
    required String time,
    required String title,
    required String content,
    bool hasImage = false,
    List<String> images = const [],
    required bool isLast,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 左侧时间
        SizedBox(
          width: 80,
          child: Padding(
            padding: const EdgeInsets.only(top: 2),  // 添加顶部内边距
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  time.substring(11), // 显示时间
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey[700],
                  ),
                ),
                Text(
                  time.substring(5, 10), // 显示日期(月-日)
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
        ),
        // 中间时间线
        Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 6),  // 调整圆点位置
              child: Container(
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(
                    color: const Color(0xFFFF5722),
                    width: 2,
                  ),
                ),
              ),
            ),
            if (!isLast)
              Container(
                width: 1,
                height: hasImage ? 120 : 56,
                margin: const EdgeInsets.only(
                  top: 4,  // 调整连接线顶部间距
                  bottom: 2,
                ),
                color: const Color(0xFFEEEEEE),
              ),
          ],
        ),
        const SizedBox(width: 16),
        // 右侧内容
        Expanded(
          child: Padding(
            padding: const EdgeInsets.only(top: 2),  // 添加顶部内边距
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  content,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                    height: 1.4,
                  ),
                ),
                if (hasImage) ...[
                  const SizedBox(height: 12),
                  SizedBox(
                    height: 80,  // 增加图片高度
                    child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      itemCount: images.length,
                      separatorBuilder: (context, index) => const SizedBox(width: 8),
                      itemBuilder: (context, index) => GestureDetector(
                        onTap: () {
                          // TODO: 查看大图
                        },
                        child: Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                            color: Colors.grey[200],
                            border: Border.all(
                              color: const Color(0xFFEEEEEE),
                            ),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(4),
                            child: Image.network(
                              images[index],
                              fit: BoxFit.cover,
                              loadingBuilder: (context, child, loadingProgress) {
                                if (loadingProgress == null) return child;
                                return Center(
                                  child: CircularProgressIndicator(
                                    value: loadingProgress.expectedTotalBytes != null
                                        ? loadingProgress.cumulativeBytesLoaded / 
                                          loadingProgress.expectedTotalBytes!
                                        : null,
                                    strokeWidth: 2,
                                    valueColor: const AlwaysStoppedAnimation<Color>(
                                      Color(0xFFFF5722),
                                    ),
                                  ),
                                );
                              },
                              errorBuilder: (context, error, stackTrace) {
                                return Icon(
                                  Icons.broken_image_outlined,
                                  color: Colors.grey[400],
                                );
                              },
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
                if (!isLast)
                  const SizedBox(height: 20),  // 增加项目间距
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 获取主操作按钮文本
  String _getMainActionText(String status) {
    switch (status) {
      case '待服务':
        return '开始服务';
      case '服务中':
        return '完成订单';
      default:
        return '查看详情';
    }
  }

  // 显示取消订单对话框
  void _showCancelOrderDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认取消订单'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('取消原因'),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                color: const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(8),
              ),
              child: TextField(
                maxLines: 3,
                decoration: const InputDecoration(
                  hintText: '请输入取消原因',
                  border: InputBorder.none,
                ),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              // TODO: 处理取消订单
              Navigator.pop(context);
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFFF5722),
            ),
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }
} 